package com.momo.cloudspringserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.momo.cloudspringserver.entity.RedisUser;
import com.momo.cloudspringserver.error.RedisKeyEnum;
import com.momo.cloudspringserver.utils.JSONResult;
import com.momo.cloudspringserver.utils.JwtTokenUtil;
import com.momo.cloudspringserver.utils.RedisUtil;
import com.momo.cloudspringserver.utils.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @program: momo-cloud
 * @description: TODO
 * @author: Jie Li
 * @create: 2019-07-17 13:57
 **/
@RestController
@RequestMapping(value = "/platform/", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@Slf4j
public class TokenController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @RequestMapping("/getToken/v1")
    public JSONResult getToken() {
        String redisUserKey = StrUtil.genUUID();
        RedisUser redisUser = RedisUser.builder().redisUserKey(redisUserKey)
                .sysUserLoginName("登录名").sysUserPhone("手机号")
                .deptId(1L).groupId(1L).id(1L)
                .sysLoginNumber(1).sysUserName("用户名").build();
        //生成token
        String jsonStr = JSONObject.toJSONString(redisUser);
        // randomKey和token已经生成完毕
        final String randomKey = jwtTokenUtil.getRandomKey();
        final String token = jwtTokenUtil.generateToken(jsonStr, randomKey);
        List<String> list = Lists.newArrayList();
        list.add(redisUserKey);
        String listStr = JSONObject.toJSONString(list);
        //redis  key--》用户id     v----》 List<String> String=uuid
        loginNumber(1L, listStr, redisUserKey, token);
        return JSONResult.ok(redisUserKey);
    }

    /**
     * @param userId   用户id
     * @param listUuid List<String> String=uuid
     * @param uuid
     * @param token
     */
    private void loginNumber(Long userId, String listUuid, String uuid, String token) {
        //redis  key--》用户id     v----》 List<String> String=uuid
        redisUtil.set(RedisKeyEnum.REDIS_KEY_USER_ID.getKey() + userId, listUuid, RedisKeyEnum.REDIS_KEY_USER_ID.getExpireTime());
        redisUtil.set(RedisKeyEnum.REDIS_KEY_USER_INFO.getKey() + uuid, token, RedisKeyEnum.REDIS_KEY_USER_INFO.getExpireTime());
    }
}
